package com.ustarlink.live;

import android.util.Log;

import java.io.BufferedInputStream;
import java.io.BufferedOutputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.net.MalformedURLException;
import java.net.URL;
import java.net.URLConnection;

/**
 * Created by cfm on 15-12-23.
 * 下载一个文件
 */
public class Downloader {
    private static String myTag = "uStarLink Live";

    static final int POST_PROGRESS = 1;
    /*************************************************
     * 下载文件从Internet 或或者本地文件
     *
     *  @param URL -所要下载的文件的URL
     *  @param fos -FileOutputStream 保存已下载的文件
     *************************************************/
    public static void DownloadFromURL(String URL, FileOutputStream fos){
        try {
            URL url = new URL(URL);

            /** 记录当前时间为以后显示花了多久来下载文件 **/
            long startTime = System.currentTimeMillis();
            Log.d(myTag,"Download Begining");

            /** 打开URL链接 **/
            URLConnection ucon = url.openConnection();

            Log.i(myTag, "Opened Connection");

            /** 定义从URLConnection读取的InputStreams **/
            InputStream is = ucon.getInputStream();
            BufferedInputStream bis = new BufferedInputStream(is);
            Log.i(myTag, "Got InputStream and BufferedInputStream");

            /** 定义输出的OutputStreams 写入的文件**/
            BufferedOutputStream bos = new BufferedOutputStream(fos);
            Log.i(myTag, "Got FileOutputStream and BufferedOutputStream");

            /** 开始读写文件 **/
            byte data[] = new byte[4096];
            int count;
            while ((count=bis.read(data)) != -1){
                bos.write(data, 0, count);
            }

            bos.flush();
            bos.close();

            Log.d(myTag, "Download ready in " +
                    ((System.currentTimeMillis()) - startTime) + " milisec" );



        } catch (MalformedURLException e) {
            Log.d(myTag, "Error:" + e);
        } catch (IOException e) {
            Log.d(myTag, "Error:" + e);
        }
    }


}
